package com.platform.modules.sys.controller;


import com.platform.common.utils.BeanUtils;
import com.platform.common.utils.NumberUtils;
import com.platform.common.utils.StringUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import com.platform.common.utils.ShiroUtils;
import com.platform.config.datascope.DataScope;
import com.platform.modules.sys.entity.SysOrgEntity;
import com.platform.modules.sys.entity.SysUserEntity;
import com.platform.modules.sys.service.SysOrgService;
import com.platform.modules.sys.service.SysRoleOrgService;

import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * Controller公共组件
 *
 * @author 肖亮
 */
@Slf4j
public abstract class AbstractController {
	protected Logger logger = log;

	@Resource
	protected HttpServletRequest request;
	@Resource
	protected HttpServletResponse response;
	@Autowired
	private SysRoleOrgService sysRoleOrgService;
	@Autowired
	private SysOrgService sysOrgService;


	/**
	 * 初始化化传入 service 的参数
	 * @param objects
	 * @return
	 */
	protected Map<String,Object> getParams(Object ... objects){
		// 初始化查询参数
		Map<String, Object> params = new HashMap<>();

		// put 分页参数
		String currPage = request.getParameter("currPage");
		String limit = request.getParameter("limit");
		if(StringUtils.isNotBlank(currPage) && StringUtils.isNotBlank(limit)){
			params.put("page", currPage);
			params.put("limit", limit);
		}

		// 将 objects 转化成 map
		if(objects!=null && objects.length > 0){
			for(Object obj : objects){
				params.putAll(BeanUtils.toMap(obj));
			}
		}
		return params;
	}


	/**
	 * @descr 当前登录用户
	 *
	 * @return SysUserEntity
	 */
	protected SysUserEntity getUser() {
		return ShiroUtils.getUserEntity();
	}

	/**
	 * @descr 当前登录用户ID
	 *
	 * @return userId
	 */
	protected String getUserId() {
		return getUser().getUserId();
	}

	/**
	 * @descr 当前登录用户所属机构ID  或者 项目ID
	 *
	 * @return orgNo
	 */
	protected String getOrgNo() {
		return getUser().getOrgNo();
	}

	
	/**
	 * @descr 当前登录用户所属机构
	 *
	 * @return orgNo
	 */
	protected SysOrgEntity getOrg() {		
		return sysOrgService.getById(getUser().getOrgNo());
	}

	
	/**
	 * @descr 数据权限构造
	 *
	 * @return DataScope
	 */
	protected DataScope getDataScope() {
		DataScope dataScope = new DataScope();
		dataScope.setOrgNos(sysRoleOrgService.queryOrgNoListByUserId(getUserId()));
		return dataScope;
	}

	/**
	 *@descr  数据权限构造
	 *
	 * @return DataScope
	 */
	protected DataScope getDataScope(String userAlias, String orgAlias) {
		DataScope dataScope = new DataScope();
		dataScope.setUserAlias(userAlias);
		dataScope.setOrgAlias(orgAlias);
		dataScope.setOrgNos(sysRoleOrgService.queryOrgNoListByUserId(getUserId()));
		return dataScope;
	}
}
